from apps import jsonrpc, jsonrpc2
from .models import db, NewsCategory, News


@jsonrpc.method("News.news_categoty")
def news_category():
    """文章分类"""
    cat_list = NewsCategory.query.filter(
        NewsCategory.is_show == True,
        NewsCategory.is_deleted == False
    ).order_by(
        db.desc(NewsCategory.sort),
        db.desc(NewsCategory.id)
    ).limit(5).all()

    data = []

    for category in cat_list:
        data.append(category.__to_dict__(["id", "name"]))

    return data


@jsonrpc.method("News.home_news")
def home_news():
    """首页潮流资讯推荐文章"""
    news_list = News.query.filter(
        News.is_recommend == True,
        News.is_show == True,
        News.is_deleted == False
    ).order_by(
        db.desc(News.sort),
        db.desc(News.id)
    ).limit(10).all()

    data = []
    for news in news_list:
        data.append(news.__to_dict__(["id", "title", "read_count", "descript", "created_time", "image_url"]))

    return data


@jsonrpc.method("News.listnews(category=Number, page=Number, per_page=Number)")
def listnews(category=0, page=1, per_page=4):
    """列表页文章列表"""
    data = {}
    try:
        query = News.query.filter(
            News.is_show == True,
            News.is_deleted == False
        ).order_by(
            db.desc(News.sort),
            db.desc(News.id)
        )

        # 分类查询
        if category > 0:
            query = query.filter(News.category_id == category)

        paginate = query.paginate(page, per_page)
        # 当前分页页码
        data["page"] = paginate.page
        # 当前页数据项
        data["items"] = []
        for item in paginate.items:
            news = item.__to_dict__(["id", "title", "read_count", "descript", "created_time", "image_url"])
            data["items"].append(news)
        # 上一页页码
        data["prev_num"] = paginate.prev_num
        # 下一页页码
        data["next_num"] = paginate.next_num
        # 是否有上一页
        data["has_prev"] = paginate.has_prev
        # 是否有下一页
        data["has_next"] = paginate.has_next
        # 总页码
        data["pages"] = paginate.pages
        # 总数据量
        data["total"] = paginate.total

    except:
        data = []

    return data


@jsonrpc.method("News.news_detail(id=Number)")
def news_detail(id):
    """详情页文章信息"""
    data = {}
    try:
        news = News.query.filter(News.id == id).first()
        news.read_count += 1
        db.session.commit()
        data = news.__to_dict__(["id", "title", "author", "content", "read_count", "created_time"])
    except:
        pass
    return data
